
import { fromPairs } from 'lodash'
export const GAP = 4 // top 2 + bottom 2 of bar instance

export const BAR_MAP = {
    vertical: {
        offset: 'offsetHeight',
        scroll: 'scrollTop',
        scrollSize: 'scrollHeight',
        size: 'height',
        key: 'vertical',
        axis: 'Y',
        client: 'clientY',
        direction: 'top',
    },
    horizontal: {
        offset: 'offsetWidth',
        scroll: 'scrollLeft',
        scrollSize: 'scrollWidth',
        size: 'width',
        key: 'horizontal',
        axis: 'X',
        client: 'clientX',
        direction: 'left',
    },
}

export const renderThumbStyle = ({
    move,
    size,
    bar,
}) => ({
    [bar.size]: size,
    transform: `translate${bar.axis}(${move}%)`,
})

export const epPropKey = '__epPropKey'
export const isEpProp = (val) => isObject(val) && !!(val)[epPropKey]

export const buildProp = (
    prop,
    key
) => {
    // filter native prop type and nested prop, e.g `null`, `undefined` (from `buildProps`)
    if (!isObject(prop) || isEpProp(prop)) return prop

    const { values, required, default: defaultValue, type, validator } = prop

    const _validator =
        values || validator
            ? (val) => {
                let valid = false
                let allowedValues = []

                if (values) {
                    allowedValues = Array.from(values)
                    if (hasOwn(prop, 'default')) {
                        allowedValues.push(defaultValue)
                    }
                    valid ||= allowedValues.includes(val)
                }
                if (validator) valid ||= validator(val)

                if (!valid && allowedValues.length > 0) {
                    const allowValuesText = [...new Set(allowedValues)]
                        .map((value) => JSON.stringify(value))
                        .join(', ')
                    warn(
                        `Invalid prop: validation failed${key ? ` for prop "${key}"` : ''
                        }. Expected one of [${allowValuesText}], got value ${JSON.stringify(
                            val
                        )}.`
                    )
                }
                return valid
            }
            : undefined

    const epProp = {
        type,
        required: !!required,
        validator: _validator,
        [epPropKey]: true,
    }
    if (hasOwn(prop, 'default')) epProp.default = defaultValue
    return epProp
}


export const definePropType = () => val

export const buildProps = (props) =>
    fromPairs(
        Object.entries(props).map(([key, option]) => [
            key,
            buildProp(option, key),
        ])
    )
